<template>
  <el-dialog :title="textMap[status]" :width="width" :visible.sync="visible">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="data"
      status-icon
      label-position="left"
      label-width="100px"
      v-loading="loading"
    >
      <slot></slot>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="loading" @click="close">取消</el-button>
      <el-button v-if="status == 'create'" :disabled="loading" type="primary" @click="createData">
        确定
      </el-button>
      <el-button v-else type="primary" :disabled="loading" @click="updateData">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'DialogForm',
  props: {
    rules: {
      type: [Object, Array],
      default: () => {
        return []
      }
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'create'
    },
    width: {
      type: String,
      default: '400px'
    }
  },
  data() {
    return {
      textMap: {
        update: '编辑',
        create: '创建'
      },
      visible: false
    }
  },
  methods: {
    open() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    close() {
      this.visible = false
    },
    createData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          this.$emit('createData')
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          this.$emit('updateData')
        }
      })
    }
  }
}
</script>
